package com.jd.service;

import com.alibaba.fastjson.JSON;
import com.jd.domain.Content;
import com.jd.utils.HtmlParseUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HtmlParseUtils htmlParseUtils;

    public Boolean parseContent(String keywords) throws IOException {
        List<Content> contents = htmlParseUtils.parseJD(keywords);
        //将查询的数据插入到es
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("200s");
        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    public List<Map<String,Object>> searchPage(String keyword,int pageNum,int pageSize) throws IOException {
        if (pageNum<=1){
            pageNum =1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder= new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termBuilder = QueryBuilders.termQuery("name", keyword);
        SearchSourceBuilder query = sourceBuilder.query(termBuilder);
        sourceBuilder.timeout(new TimeValue(200, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //数据处理
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits()) {
                list.add(hit.getSourceAsMap());
        }

        return list;
    }
    public List<Map<String,Object>> searchHeightPage(String keyword,int pageNum,int pageSize) throws IOException {
        if (pageNum<=1){
            pageNum =1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder= new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termBuilder = QueryBuilders.termQuery("name", keyword);
        SearchSourceBuilder query = sourceBuilder.query(termBuilder);
        sourceBuilder.timeout(new TimeValue(200, TimeUnit.SECONDS));

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.postTags("</span>");
        highlightBuilder.field("name");
        sourceBuilder.highlighter(highlightBuilder);


        //执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //数据处理
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (name!=null){
                Text[] fragments = name.fragments();
                String temp="";
                for (int i = 0; i < fragments.length; i++) {
                    temp+=fragments[i];
                }
                sourceAsMap.put("name",temp);
            }
            list.add(sourceAsMap);

        }

        return list;
    }
}
